<!--
 * @Descripttion: 销售明细报表列表
 * @version:
 * @Author: cxguo
 * @Date: 2019-08-02 15:03:05
 * @LastEditors: cxguo
 * @LastEditTime: 2020-11-06 10:36:39
 -->
<template>
  <div class="app-container">
    <div class="clearfix">
      <el-card shadow="never" class="oper-btn-card">
        <div class="clearfix">
          <el-form
            class="fl form-no-bottom"
            :inline="true"
            :model="searchData"
            label-position="left"
            label-width="80px"
            @keydown.enter.native="btnSearch"
          >
            <el-form-item>
              <el-date-picker
                v-model="dataObj.rangeDate"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                @change="onDateChange"
              />
              <el-button type="primary" :loading="btnLoading.search" @click="btnSearch()">
                搜索
              </el-button>
              <el-button type="default" @click="isFilterOpen = !isFilterOpen">
                {{ btnFilterOpenText }}
              </el-button>
            </el-form-item>
          </el-form>
          <!-- <el-button class="fr" type="default" @click="btnExportData">导 出</el-button> -->
        </div>
        <SearchFilter
          v-if="isFilterOpen"
          :search="btnFilterSearch"
          :clear="btnClearConditions"
        >
          <Conditions ref="conditions" />
        </SearchFilter>
      </el-card>
    </div>
    <div class="margin-t2">
      <vxe-grid
        ref="table"
        class="grid"
        border
        resizable
        highlight-hover-row
        :loading="tableLoading.table"
        :columns="columnsData"
        :data="tableData.table"
      />
    </div>
    <div class="pagination-container">
      <el-pagination
        background
        layout="total, sizes,prev, pager, next,jumper"
        :page-size="pageInfo.rows"
        :page-sizes="[20,30,40]"
        :current-page.sync="pageInfo.page"
        :total="pageInfo.total"
        @size-change="onSizeChange"
        @current-change="onCurrentChange"
      />
    </div>
  </div>
</template>
<script>
import { oftenuse } from '@/libs/mixins'
import { listSaleDetail } from '@/api/report/sale-detail.js'
import SearchFilter from '@/views/components/SearchFilter'
import Conditions from './conditions'

export default {
  name: 'ReportSaleDetail',
  filters: {
  },
  components: { SearchFilter, Conditions },
  mixins: [oftenuse],
  data() {
    return {
      currentId: null,
      searchData: {},
      optionsData: {},
      isFilterOpen: false,
      columnsData: [
        { title: '序号', width: 60, fixed: 'left', align: 'center',
          slots: {
            default: (params) => {
              const { seq } = params
              const value = seq
              return [<span>{value}</span>]
            }
          }
        },
        { field: 'billCatName', title: '单据类型', width: 100, fixed: 'left', align: 'center' },
        { field: 'skuName', title: '商品名称', width: 200, fixed: 'left', showOverflow: true },
        { field: 'businessTime', title: '业务日期', width: 100 },
        { field: 'deliveryDate', title: '送货日期', width: 100 },
        { field: 'billNo', title: '单据编号', width: 160,
          slots: {
            default: (params) => {
              const _this = this
              const { billId, billNo, direction } = params.row
              const data = {
                props: {
                  type: 'primary'
                },
                on: {
                  click: function(e) {
                    if (direction === '0') {
                      _this.$router.push({
                        name: 'SaleDetail',
                        query: { billId: billId }
                      })
                    }
                    if (direction === '1') {
                      _this.$router.push({
                        name: 'SaleReturnDetail',
                        query: { billId: billId }
                      })
                    }
                  }
                }
              }
              if (billNo) {
                return [<el-link {...data}>{billNo}</el-link>]
              }
            }
          }},
        { field: 'comegoName', title: '客户名称', width: 200, showOverflow: true },
        { field: 'unitName', title: '单位', width: 100 },
        { field: 'quantity', title: '数量', width: 100 },
        { field: 'price', title: '单价', width: 120 },
        { field: 'amountTax', title: '税额', width: 120 },
        { field: 'amountPayable', title: '金额', width: 120 },
        { field: 'priceCostTotal', title: '成本金额', width: 120,
          slots: {
            default: ({ row }) => {
              const amountDiscountOnThisGood = this.getAmountDiscountOnGood(row)
              const { priceCost, unitMulti, quantity } = row
              const priceCostTotal = this.$amount(priceCost).multiply(unitMulti).multiply(quantity)
              const value = this.$amount(priceCostTotal).add(amountDiscountOnThisGood).format()
              return [<span>{value}</span>]
            },
            header: ({ column }) => {
              return [
                <el-tooltip effect='dark' content='成本金额 =（ 商品成本价 + 单位分摊成本 ）* 数量' placement='top-end'>
                  <span>成本金额<i class='color-bule el-icon-question'/></span>
                </el-tooltip>
              ]
            }
          }
        },
        { field: 'amountPayableReal', title: '成交单价', width: 120,
          slots: {
            default: ({ row }) => {
              const amountDiscountOnThisGood = this.getAmountDiscountOnGood(row)
              const { price, quantity } = row
              const amountDiscountOnThisGoodAvg = this.$amount(amountDiscountOnThisGood).divide(quantity)
              const value = this.$amount(price).subtract(amountDiscountOnThisGoodAvg).format()
              return [<span>{value}</span>]
            },
            header: ({ column }) => {
              return [
                <el-tooltip effect='dark' content='成交单价 = 该商品已平摊整单折扣后，计算出的商品真实成交单价' placement='top-end'>
                  <span>成交单价<i class='color-bule el-icon-question'/></span>
                </el-tooltip>
              ]
            }
          }
        },
        { field: 'amountDiscountAvg', title: '平摊整单优惠金额', width: 140,
          slots: {
            default: ({ row }) => {
              const value = this.getAmountDiscountOnGood(row)
              return [<span>{value}</span>]
            },
            header: ({ column }) => {
              return [
                <el-tooltip effect='dark' content='平摊整单优惠金额 = 该商品占整单的优惠金额' placement='top-end'>
                  <span>平摊整单优惠金额<i class='color-bule el-icon-question'/></span>
                </el-tooltip>
              ]
            }
          }
        },
        { field: 'amountPayableThisGood', title: '成交金额', width: 120,
          slots: {
            default: ({ row }) => {
              const { price, quantity } = row
              const amountDiscountOnGood = this.getAmountDiscountOnGood(row)
              const amountPayableThisGood = this.$amount(price).multiply(quantity).format()
              const value = this.$amount(amountPayableThisGood).subtract(amountDiscountOnGood).format()
              return [<span>{value}</span>]
            }
          }
        },
        { field: 'remarks', title: '备注', width: 120, showOverflow: true,
          slots: {
            default: ({ row }) => {
              const value = row.remarks
              return [<span>{value}</span>]
            },
            header: ({ column }) => {
              return [
                <el-tooltip effect='dark' content='备注 = 该商品在单据中的备注' placement='top-end'>
                  <span>备注<i class='color-bule el-icon-question'/></span>
                </el-tooltip>
              ]
            }
          }
        },
        { field: 'billRelationNo', title: '关联单据编号', width: 120 },
        { field: 'comegoCode', title: '客户编号', width: 140 },
        { field: 'comegoCatName', title: '客户分类', width: 120 },
        { field: 'skuCode', title: '商品编号', width: 150 },
        { field: 'skuCatName', title: '商品分类', width: 120 },
        { field: 'barcode', title: '商品条码', width: 150 },
        { field: 'handUserName', title: '经手人', width: 120 },
        { field: 'createUserName', title: '制单人', width: 120 }
        // { field: 'isGift', title: '是否赠品', width: 120 }
      ]
    }
  },
  computed: {
    'btnFilterOpenText': function() {
      return this.isFilterOpen ? '收起筛选' : '展开筛选'
    }
  },
  watch: {
  },
  created() {
    this.listData()
  },
  methods: {
    btnExportData() {
      this.$router.push({
        name: 'SaleReturnAdd'
      })
    },
    btnSearch() {
      this.setBtnLoading('search', true)
      this.pageInfo.current = 1
      this.listData().then(res => {
        this.setBtnLoading('search', false)
      }).catch(err => {
        console.log(err)
        this.setBtnLoading('search', false)
      })
    },
    btnClearConditions() {
      this.$refs.conditions.clearData()
    },
    btnFilterSearch() {
      this.setBtnLoading('search', true)
      this.pageInfo.current = 1
      const searchData = this.$refs.conditions.searchData
      const params = {
        data: searchData,
        page: this.pageInfo
      }
      this.listData(params).then(res => {
        this.setBtnLoading('search', false)
      }).catch(err => {
        this.$message.error('查询异常:', err.message)
        this.setBtnLoading('search', false)
      })
    },
    // api
    /**
     * 平摊整单优惠金额
     * 算法： 单据折扣总额 *（商品金额/单据总额）
     */
    getAmountDiscountOnGood(row) {
      const { quantity, price, amountDiscount, amountPayable } = row
      const anountOnThisGood = this.$amount(quantity).multiply(price)
      const dis = this.$amount(anountOnThisGood).divide(amountPayable).format()
      const value = this.$amount(amountDiscount).multiply(dis).format()
      return value
    },
    listData(params = { data: this.searchData, page: this.pageInfo }) {
      if (params.data.date) {
        const data = params.data
        data.beginTime = data.date[0]
        data.endTime = data.date[1]
      }
      this.setTableLoading('table', true)
      return new Promise((resolve, reject) => {
        listSaleDetail(params).then(res => {
          this.setTableLoading('table', false)
          if (!res.data.flag) return reject(new Error(res.data.message))
          const { records, total } = res.data.data
          this.setTableData('table', records)
          this.pageInfo.total = total
          resolve(res)
        }).catch(err => {
          reject(err)
          this.setTableLoading('table', false)
        })
      })
    },
    onSizeChange(val) {
      this.pageInfo.current = 1
      this.pageInfo.size = val
      this.listData()
    },
    onCurrentChange(val) {
      this.pageInfo.current = val
      this.listData()
    },
    onDateChange() {
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">

</style>
